const validate = require("../middleware/validate");
const ResponseMessage = require("../response/message");

const log4js = require("log4js");
const logger = log4js.getLogger();

const { query,body } = require("express-validator");

function checkQueryExists(req,res,msgs = ["缺失查询字符串参数","缺少 query 查询字符串参数"]){
    if(!req.query){
        logger.warn(req.ip + " - " + req.method + " - " + req.originalUrl + " - "+msgs[0])
        res.send(new ResponseMessage(400, msgs[1], {}));
     }
}


exports.tradePriceParamsValidator = (req, res, next) => {
    checkQueryExists(req,res);
    validate([
         query("cycleType").notEmpty().withMessage("时间范围类型不能为空"),
    ])(req,res,next)
}

exports.getOrderInfosParamsValidator = (req,res,next) => {
    checkQueryExists(req,res);
    (async (callback) => {
       validate([
           query("searchContent").optional().notEmpty().withMessage("搜索的内容不能为空"),
           query("pageIndex").optional().notEmpty().withMessage("当前页不能为空").bail().custom(callback("页码必须是数字")),
           query("pageSize").optional().notEmpty().withMessage("页大小不能为空").bail().custom(callback("页大小必须是数字"))
      ])(req,res,next)
    })((msg) => {
        return async (value)=>{
           if(!/\d/.test(value)){
               return Promise.reject(msg);
           }
        }
    })
}

exports.deleteOrderParamsValidator = async (req,res,next) => {
    checkQueryExists(req,res);
    validate([
        query("id").notEmpty().withMessage("ID 不能为空")
    ])(req,res,next);
}

exports.findOrderByOrderNoParamsValidator = async (req,res,next) => {
    checkQueryExists(req,res);
    validate([
        query("orderNo").notEmpty().withMessage("订单号不能为空")
    ])(req,res,next);
}

exports.addOrderParamsValidator = async (req,res,next) => {
    if(!req.body){
        logger.warn(req.ip + " - " + req.method + " - " + req.originalUrl + " - 缺少请求体")
        res.send(new ResponseMessage(400, "缺少请求体", {}));
    }
    validate([
        body("orderNo").notEmpty().withMessage("订单编号"),
        body("toId").notEmpty().withMessage("收款人ID不能为空"),
        body("toName").notEmpty().withMessage("收款人姓名不能为空"),
        body("fromId").notEmpty().withMessage("付款人ID不能为空"),
        body("fromName").notEmpty().withMessage("付款人姓名不能为空"),
        body("tradeType").notEmpty().withMessage("交易类型不能为空"),
        body("tradeMoney").notEmpty().withMessage("交易金额不能为空"),
        body("tradeDesc").notEmpty().withMessage("订单备注不能为空"),
        ])(req,res,next)
}